import React, { FC, useEffect, useState } from 'react'
import { Button, Drawer, Transfer } from 'antd'
import { projectDetail, projectUpdate } from '@/services/project'
import { getSuperFileList } from '@/services/proTable'
import ProCard from '@ant-design/pro-card'

interface TableGenConfigProps {
  visible:boolean,
  onClose:any,
  projectId:string,
}

const TableGenConfig: FC<TableGenConfigProps> = (props) => {

  const { visible, onClose, projectId } = props
  const [mockData, setMockData] = useState<any>([])
  const [targetKeys, setTargetKeys] = useState<any>([])

  useEffect(() => {
    if (visible) {
      projectDetail(projectId).then(res => {
        if (res.code === 10000) {
          let targetKey = []
          const ignoreTables = res.data?.ignore_tables || false
          if (ignoreTables) {
            targetKey = JSON.parse(ignoreTables)
            setTargetKeys(targetKey)
          }
        }
      })

      getSuperFileList({ project_id: projectId, flag: 'no' }).then((res) => {
        if (res.code === 10000) {
          const result = res.data
          const data = []
          for (const item of result) {
            const val = {
              key: item.id.toString(),
              title: item.name,
              description: item.comment
            }
            data.push(val)
          }
          setMockData(data)
        }
      })

    }
  }, [visible, projectId])


  const handleChange = (targetKey: any, direction: any, moveKeys: any) => {
    console.log(targetKey, direction, moveKeys)
    let ignoreTables = targetKey.filter((item: any) => Object.prototype.toString.call(item) != '[object Object]')
    ignoreTables = JSON.stringify(ignoreTables)
    console.log(ignoreTables)

    projectUpdate({ id: projectId, ignore_tables: ignoreTables }).then((res) => {
      if (res.code === 10000) {
        setTargetKeys(targetKey)
      }
    })
  }

  const renderItem = (item: any) => {
    const customLabel = (
      <span className="custom-item">
        {item.title} - {item.description}
      </span>
    )

    return {
      label: customLabel, // for displayed item
      value: item.title // for title and filter matching
    }
  }

  return (
    <Drawer
      title="数据库表管理"
      width={800}
      onClose={() => onClose(false)}
      visible={visible}
      bodyStyle={{ paddingBottom: 80, backgroundColor: '#f0f2f5' }}
      footer={
        <div
          style={{
            textAlign: 'right'
          }}
        >
          <Button onClick={() => onClose(false)} type="primary">
            关闭
          </Button>
        </div>
      }>
      <ProCard title='配置'>
        <Transfer
          dataSource={mockData}
          listStyle={{
            width: 300,
            height: 400
          }}
          targetKeys={targetKeys}
          onChange={handleChange}
          render={renderItem}
        />
      </ProCard>
    </Drawer>
  )
}

export default TableGenConfig
